﻿@model Jb.Web.ViewModels.JobApplicationViewModel
@using Jb.Web.Utility;
@using Jb.Common.Extensions;

@{    
    Jb.Web.ViewModels.JobViewModel _Job = Model != null ? Model.Job : null;
    int _JobSeekerID = UserInfo.IsJobSeeker ? SessionCache.CurrentUser.JobSeekerID : 0;
    
    String pageTitle = _Job == null ? "Apply to Job" : "Apply to Job: " + _Job.Title;
    ViewBag.Title = Html.GetPageTitle(pageTitle);	
	bool _HasSaved = ViewData.HasSaved();
    bool _IsPost = WebUtil.GetQueryStringBoolean("IsPost");
    bool _IsSaved = WebUtil.GetQueryStringBoolean("IsSaved");
    int _SaveStatus = WebUtil.GetQueryStringInt("Status");
    Jb.Domain.Resume _Resume = null;
    if(Model != null && Model.ResumeID > 0){
        Jb.Domain.JbEntities context = new Jb.Domain.JbEntities();
        _Resume = context.Resumes.FirstOrDefault(P => P.ID == Model.ResumeID);
    }
    bool _HasAppliedPreviously = Jb.Common.DB.NullHandler.GetBoolean(ViewData[AppConstants.ViewDataKeys.GENERIC_KEY]);
    ///Warning Message Section Starts
    System.Text.StringBuilder _Warning = new System.Text.StringBuilder();
    if(UserInfo.IsJobSeeker && !SessionCache.CurrentUser.JobSeekerInfo.HasProfileCompleted){
        _Warning.AppendFormat("You cannot apply on this job because of the following reason(s):");
        _Warning.AppendFormat("<ul>");
        _Warning.AppendFormat("<li>You haven't completed your Job Seeker profile. <a href='/JobSeeker/Home/ProfileEdit' class='btn'><i class='icon-user'></i> Build your profile now</a></li>");        
    }
    if(UserInfo.IsJobSeeker && SessionCache.CurrentUser.JobSeekerInfo.TotalResumes <= 0){
        if(_Warning.Length == 0){
            _Warning.AppendFormat("You cannot apply on this job because of the following reason(s):");
            _Warning.AppendFormat("<ul>");
        }
        _Warning.AppendFormat("<li>You haven't uploaded any resume to send with this job application. <a href='/JobSeeker/Resume/Edit' class='btn'><i class='icon-plus'></i> Add new Resume</a></li>");
    }
    if(_Warning.Length > 0){
        _Warning.AppendFormat("</ul>");
    }
}

<div class="jb-page-heading">
    <h1>@pageTitle</h1>
    <div>Enter necessary information and then click the Apply button to apply to this job.</div>
</div>
<div class="jb-page-content">
@using (Html.BeginForm("Apply", "Job", FormMethod.Post, new { id = "frmApply"}))
{
    if (_IsPost)
    {
        if (_IsSaved)
        {
            @Html.SuccessMessageBox("Congratulations! You have successfully applied to this job. If you are short listed then employer will contact with you for the interview. Thanks for being with us.")
        }
        else {
            @Html.WarningMessageBox("Sorry! Something went wrong and we could not send your job application. Please try again later.")
        }
    }
    else
    {
        @Html.ValidationSummary(true)

        if (!UserInfo.IsJobSeeker)
        {
            @: @Html.WarningMessageBox("Please <a href='/Account/Logon'>login</a> or <a href='/Registration/JobSeeker'>register</a> as a job seeker to apply to this job.")
            if (_Job != null)
            {
                SessionCache.RedirectUrl = String.Format("/Job/Apply/{0}", _Job.ID);
            }
        }
        else if (Model == null || _Job == null)
        {
            @: @Html.WarningMessageBox("Sorry! Requested Job was not found.")
        }
        else if (_Job.EndDate.ToDateTime(ConfigReader.CSharpCalendarDateFormat) < DateTime.Now)
        {
            @: @Html.WarningMessageBox("Sorry! This job has already expired, you can not apply to it.")
        }
        else if(_HasAppliedPreviously){
            @: @Html.WarningMessageBox("Sorry! You have already applied to this job and employers are taking care of your application, no need to apply again.")
        }
        else
        {
            if (_HasSaved)
            {
            @Html.SuccessMessageBox("Congratulations! Your Job Application has sent successfully.")
            }
            else if (ViewData[AppConstants.ViewDataKeys.SAVED] != null && !_HasSaved)
            {
            @Html.WarningMessageBox("Sorry! Something went wrong, we could not sent your Application.")
            }
            ///Very very strange thing is happening here, the Model.ID is getting the value of Model.JobID property with Html.HidderFor helper.
            ///Probably this is a ASP .NET MVC3 bug, so doing following workaround.
            @*@Html.Hidden("ID", Model.ID)
		    @Html.HiddenFor(model => model.ID)*@
            <input type="hidden" id="ID" name="ID" value="@(Model.ID)" />
            @Html.HiddenFor(model => model.JobID)
            @Html.HiddenFor(model => model.DefaultCoverLetter.Title)
            @Html.HiddenFor(model => model.DefaultCoverLetter.IsDefault)
            @Html.HiddenFor(model => model.DefaultCoverLetter.Application)

            if (_Warning.Length > 0) {
                @Html.WarningMessageBox(_Warning.ToString())
            }
            <div class="jb-group-title">Short Job Information</div>
            <div class="editor-label jb-label-hint">
                <ul>
                    <li><b>Job Title:</b> @WebUtil.FormatData(_Job.Title)</li>
                    <li><b>Company:</b> <a href="/@_Job.Company.Url" target="_blank">@_Job.Company.Name</a></li>
                    <li><b>Posted On:</b> @WebUtil.FormatData(_Job.PostDate.ToDateTime(ConfigReader.CSharpCalendarDateFormat))</li>
                    <li><b>Expires On:</b> @WebUtil.FormatData(_Job.EndDate.ToDateTime(ConfigReader.CSharpCalendarDateFormat))</li>
                </ul>
            </div>		
		    <div class="jb-group-title">
			    @Html.LabelFor(model => model.CoverLetter)                        
		    </div>
		    <div class="editor-field">
                <div class="jb-label-hint">You can select a previously saved cover letter from the list below. Your default cover letter should be pre selected.</div>
                @Html.DropDownListFor(model => model.DefaultCoverLetter.ID, BindSelectList.CoverLetters(_JobSeekerID))
                <div class="jb-label-hint">Or you can enter a coverletter below. Offcourse you can save it for future reference.</div>
			    @Html.TextAreaFor(model => model.CoverLetter, new { @class = "jb-long-text" })            
                <div><button type="button" class="btn" onclick="ConfirmSaveCoverLetter();"><i class="icon-hdd"></i> Save this Cover Letter</button></div>
                @Html.ValidationMessageFor(model => model.CoverLetter)
		    </div>
            <div class="jb-group-title">
			    @Html.LabelFor(model => model.ResumeID)            
		    </div>
		    <div class="editor-field">
                <div class="jb-label-hint">Your default resume should be pre selected.</div>
			    @Html.DropDownListFor(model => model.ResumeID, BindSelectList.Resumes(_JobSeekerID))
			    @Html.ValidationMessageFor(model => model.ResumeID)
		    </div>
            <div class="jb-group-title">
			    Resume Snap Shot
		    </div>
            <div id="divResumeSnapShot">
                @if (_Resume != null)
                {
                    @Html.Raw(WebUtil.FormatData(_Resume.SnapShot))
                }
            </div>
    
            <div class="jb-group-title"></div>
		    <div class="jb-button-container">
			    <button class="btn btn-primary" type="submit" data-loading-text="Saving..."><i class="icon-thumbs-up icon-white"></i> Apply</button>
		    </div>		
        }
    }
}
</div>

@*Save Coverletter Modal Popup Section Start*@
<div id="divSaveCoveLetterDialog" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="divPhotoEditModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">X</button>
        <h4 id="mySFLabel">Save Cover Letter</h4>
    </div>
    <div class="modal-body jb-inline-label">            
        <div id="divSFMesssage">        
            @using (Html.BeginForm("SaveCoverLetter", "Ajax", FormMethod.Post, new { id = "frmSaveCoverLetter" }))
            {
                <div>
                    <input type="text" name="CoverLetterTitle" id="CoverLetterTitle" value="" placeholder="Cover Letter Title" data-val="true" maxlength="250"
                        data-val-required="Please Enter Cover Letter Title" data-val-length-max="250" data-val-length="Title can be maximum 250 characters long."/>
                    <span data-valmsg-replace="true" data-valmsg-for="CoverLetterTitle" class="field-validation-valid"></span>
                </div>
                <div id="divServerMessage"></div>
            }
        </div>
    </div>
    <div class="modal-footer">               
        <button type="button" class="btn btn-primary" onclick="SaveCoverLetter();"><i class="icon-hdd icon-white"></i> Save Cover Letter</button>
        <button class="btn" data-dismiss="modal" aria-hidden="true"><i class="icon-off"></i> Close</button>
    </div>
</div>
@*Save Coverletter Modal Popup Section Ends*@

@section RightSideBar
{
<div style="height:400px; margin-left: 15px;"><h1>Space for rent</h1></div>
}

@section JavaScriptPlaceHolder
{
@Html.JavaScript("jquery.validate.min.js", Url)
@Html.JavaScript("jquery.validate.unobtrusive.min.js", Url)
@Html.JavaScript("Common.js", Url)

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $('#DefaultCoverLetter_ID').change(function () {
            if ($(this).val() == '0')
                $('#CoverLetter').val('');
            else {
                ShowLoadingAnimation(false);
                Ajax('@Url.PublicUrl("GetApplication", "Ajax")', 'ID=' + $(this).val(), function (result) {
                    HideLoadingAnimation();
                    $('#CoverLetter').val(result);
                });
            }
        });
        $('#ResumeID').change(function () {
            if ($(this).val() == '0')
                $('#divResumeSnapShot').html('');
            else {
                ShowLoadingAnimation(false);
                Ajax('@Url.PublicUrl("GetResumeSnapShot", "Ajax")', 'ID=' + $(this).val(), function (result) {
                    HideLoadingAnimation();
                    $('#divResumeSnapShot').html(result);
                });
            }
        });        
    });
    function ConfirmSaveCoverLetter() {
        if ($('#frmApply').valid()) {
            $('#divSaveCoveLetterDialog').modal({ show: true });
            $('#divServerMessage').html('');
        }
    }    
    function SaveCoverLetter() {
        if ($('#frmSaveCoverLetter').valid()) {
            ShowLoadingAnimation(false);
            var coverLetter = $('#CoverLetter').val(); var title = $('#CoverLetterTitle').val();
            Ajax('@Url.PublicUrl("SaveCoverLetter", "Ajax")', 'title=' + title + '&application=' + coverLetter, function (result) {
                HideLoadingAnimation();
                var status = parseInt(result);
                var html = '';
                if (status > 1) {
                    html = SuccessMessageBox('Congratulations! Your Cover Letter Saved Successfully.');
                    $('#DefaultCoverLetter_ID').append($('<option></option>').attr('value', status).text(title));
                    $('#CoverLetterTitle').val('');
                    $('#DefaultCoverLetter_ID').val(status);
                }
                else {
                    if (status == -1)
                        html = WarningMessageBox('Sorry! You have reached your cover letter saving quota. You cannot save any more cover letter.');
                    else if (status == -2)
                        html = WarningMessageBox('Sorry! You need to log in as a job seeker to save this cover letter. Probably your session has expired, please re log in.');
                    else
                        html = WarningMessageBox('Sorry! Something went wrong, we could not save your cover letter.');
                }
                $('#divServerMessage').html(html);
            });
        }
    }
</script>
}

